<?php

namespace App\Services\DataV;

use App\Models\OpenWechat\WechatUser;
use App\Models\Panx\Device;
use App\Models\Panx\Product;
use App\Models\Panx\Sex;
use App\Models\Panx\SkinDetector;
use App\Models\Store\HmSkinRecord;
use App\Models\Store\SkinRecord;
use App\Models\Store\Store;
use App\Services\Repositories\SkinRecord\SkinRecordRepository;
use Carbon\Carbon;
use Illuminate\Support\Collection;


/**
 * ali DataV 数据
 * Class DataVRepository
 * @package App\Services\DataV
 */
class DataVRepository
{
    protected $wechat_user;
    protected $product;
    protected $devices;
    protected $store;

    public function __construct()
    {
        $this->wechat_user = new WechatUser();
        $this->product = new Product();
        $this->devices = new Device();
        $this->store = new Store();
    }

    /**
     * @return array
     */
    public function getGenderRatio(): array
    {
        $male = $this->wechat_user->where('sex', Sex::MALE)->count();
        $female = $this->wechat_user->where('sex', Sex::FEMALE)->count();
        $unknown = $this->wechat_user->where('sex', Sex::UNKNOWN)->count();

        return [
            [
                'sex'   => trans('service.male'),
                'count' => $male,
            ],
            [
                'sex'   => trans('service.female'),
                'count' => $female,
            ],
            [
                'sex'   => trans('service.unknown'),
                'count' => $unknown,
            ],
        ];
    }

    /**
     * @return array
     */
    public function getAgeRatio(): array
    {

//        dd(
//            $this->normalizeAgeYear(Carbon::now()->subYear(45)->toDateString(),12),
//            $this->normalizeAgeYear(Carbon::now()->subYear(44)->toDateString(),1),
//            $this->normalizeAgeYear(Carbon::now()->subYear(35)->toDateString(),12),
//            $this->normalizeAgeYear(Carbon::now()->subYear(34)->toDateString(),1),
//            $this->normalizeAgeYear(Carbon::now()->subYear(25)->toDateString(),12),
//            $this->normalizeAgeYear(Carbon::now()->subYear(24)->toDateString(),1),
//            $this->normalizeAgeYear(Carbon::now()->subYear(18)->toDateString(),12),
//            $this->normalizeAgeYear(Carbon::now()->subYear(17)->toDateString(),1),
//            Carbon::now()->toDateString()
//        );
//        dd(Carbon::now()->subYear(18)->toDateString());

        $more_than_45 = $this->wechat_user->where([
            ['born_at', '<=', $this->normalizeAgeYear(Carbon::now()->subYear(45)->toDateString(), 12)]
        ])->count();

        $years_old_35_44 = $this->wechat_user->where([
            ['born_at', '>=', $this->normalizeAgeYear(Carbon::now()->subYear(44)->toDateString())],
            ['born_at', '<', $this->normalizeAgeYear(Carbon::now()->subYear(35)->toDateString(), 12)],
        ])->count();

        $years_old_25_34 = $this->wechat_user->where([
            ['born_at', '>=', $this->normalizeAgeYear(Carbon::now()->subYear(34)->toDateString())],
            ['born_at', '<', $this->normalizeAgeYear(Carbon::now()->subYear(25)->toDateString(), 12)],
        ])->count();

        $years_old_18_24 = $this->wechat_user->where([
            ['born_at', '>=', $this->normalizeAgeYear(Carbon::now()->subYear(24)->toDateString())],
            ['born_at', '<', $this->normalizeAgeYear(Carbon::now()->subYear(18)->toDateString(), 12)],
        ])->count();

        $less_than_18 = $this->wechat_user->where([
            ['born_at', '>', $this->normalizeAgeYear(Carbon::now()->subYear(17)->toDateString())],
            ['born_at', '<', Carbon::now()->toDateString()],
        ])->count();

        $unknown = $this->wechat_user->where('born_at', null)->orWhere('born_at', '')->count();

        $future_people = $this->wechat_user->where('born_at', '>', Carbon::now()->toDateString())->count();

//        $x = array_merge($more_than_45, $years_old_35_44, $years_old_25_34, $years_old_18_24, $less_than_18, $unknown);
//
//        $no = $this->wechat_user->whereNotIn('id', $x)->pluck('id');
//
//        dd($no, $x);


        return [
            [
                'age_range' => trans('service.age_range_45'),
                'count'     => $more_than_45,
            ],
            [
                'age_range' => trans('service.age_range_35'),
                'count'     => $years_old_35_44,
            ],
            [
                'age_range' => trans('service.age_range_25'),
                'count'     => $years_old_25_34,
            ],
            [
                'age_range' => trans('service.age_range_24'),
                'count'     => $years_old_18_24,
            ],
            [
                'age_range' => trans('service.age_range_18'),
                'count'     => $less_than_18,
            ],
            [
                'age_range' => trans('service.age_range_new'),
                'count'     => $future_people,
            ],
            [
                'age_range' => trans('service.age_range_unknown'),
                'count'     => $unknown,
            ],
        ];
    }

    private function normalizeAgeYear(string $year_data, $index = 1)
    {
        $index = $index === 1 ? '-01-01' : '-12-31';
        return explode('-', $year_data)[0] . $index;
    }

    public function getSingleProductListRatio($limit = 20): array
    {
        /** @var Collection $products */
        $products = $this->product->orderBy('try_on', 'DESC')->limit($limit)->select(['try_on', 'title'])->get();

        $data = [];
        foreach ($products as $product) {
            $data[] = [
                'area'      => $product->title,
//                'pv'  => 1,
                'attribute' => $product->try_on,
            ];
        }

        return $data;
    }

    public function getWechatUserRatio()
    {
        return [
            [
                'name'  => '',
                'value' => $this->wechat_user->count(),
            ],
        ];
    }

    public function getStoreRatio()
    {
        return [
            [
                'name'  => '',
                'value' => $this->store->count(),
            ],
        ];
    }

    public function getDeviceRatio()
    {
        return [
            [
                'name'  => '',
                'value' => $this->devices->count(), // 设备开启：设备卖出记录num总量？
            ],
        ];
    }

    public function getWaxRatio()
    {

        $skin_record_ids = (new SkinRecord())
            ->where('skin_detector_id', SkinDetector::ID_WAX)
            ->latest()
            ->pluck('id')
            ->all();

        $skin_records = (new SkinRecordRepository())->getSkinRecords(SkinDetector::ID_WAX, $skin_record_ids);

        $data = [];

        foreach ($skin_records as $skin_record) {
            $data[] = [
                's'         => 1, // 对应DataV的系列值
                'name'      => $skin_record['value'],
                'avg_value' => sprintf("%.2f", collect($skin_record['skin_records'])->avg('value')),
            ];
        }

        return $data;
    }

    public function getHmRatio()
    {

        $skin_record_ids = (new SkinRecord())
            ->where('skin_detector_id', SkinDetector::ID_HM)
            ->latest()
            ->pluck('id')
            ->all();

        $skin_records = (new SkinRecordRepository())->getSkinRecords(SkinDetector::ID_HM, $skin_record_ids);

        $hm_skin_records = [];

        foreach ($skin_records as $skin_record) {
            $hm_skin_records[] = [
                's'     => $skin_record['key'],
                'name'  => $skin_record['value'],
                'flex'  => sprintf("%.2f", collect($skin_record['skin_records'])->avg('flex')),
                'oil'   => sprintf("%.2f", collect($skin_record['skin_records'])->avg('oil')),
                'water' => sprintf("%.2f", collect($skin_record['skin_records'])->avg('water')),
            ];
        }

        $data_v_data = array_merge(
            $this->normalizeHmRatio(HmSkinRecord::POSITION_EYE, $hm_skin_records),
            $this->normalizeHmRatio(HmSkinRecord::POSITION_CHEEK, $hm_skin_records),
            $this->normalizeHmRatio(HmSkinRecord::POSITION_NECK, $hm_skin_records),
            $this->normalizeHmRatio(HmSkinRecord::POSITION_HAND, $hm_skin_records)
        );

        return $data_v_data;

    }

    private function normalizeHmRatio($series, $hm_skin_records)
    {

        $collect_hm_skin_records = collect($hm_skin_records);
        return [
            [
                's'       => $series,
//                's_value' => HmSkinRecord::HM_SKIN_RECORD_POSITIONS['zh'][$series],
                'name'    => trans('service.oil'),
                'value'   => $collect_hm_skin_records->where('s', $series)->first()['oil'],
            ],
            [
                's'       => $series,
//                's_value' => HmSkinRecord::HM_SKIN_RECORD_POSITIONS['zh'][$series],
                'name'    => trans('service.moisture'),
                'value'   => $collect_hm_skin_records->where('s', $series)->first()['water'],
            ],
            [
                's'       => $series,
//                's_value' => HmSkinRecord::HM_SKIN_RECORD_POSITIONS['zh'][$series],
                'name'    => trans('service.flex'),
                'value'   => $collect_hm_skin_records->where('s', $series)->first()['flex'],
            ]
        ];
    }


}
